package src;

import java.net.*;
import java.util.*;
import java.io.*;

public class Main {
	private static ServerSocket server;

	public static void main(String[] args) {
		Scanner scann = new Scanner(System.in);

		System.out.println("Please input server address(IP):");
		String ip = scann.next();

		System.out.println("Please input server listener(PORT):");
		int port = scann.nextInt();

		try
		{
			server = new ServerSocket(2020);
		}
		catch (IOException e)
		{e.printStackTrace();}

		while(true) {
			try {
				Socket socket = new Socket(Inet4Address.getByName(ip), port);

				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

				runOnBack();

				System.out.println("say to server:");
				String msg = scann.nextLine();

				bw.write(msg,0,msg.length());
				bw.flush();
				bw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static void runOnBack() {
		new Thread(new Runnable() {
				@Override
				public void run() {
					try {

						int i = 0;

						Socket socket = server.accept();
						System.out.println("is conn");

						if(i == 0) {
							System.out.println("(" + socket.getInetAddress().getHostAddress() + ") is connected success");
						}

						i++;

						InputStream is = socket.getInputStream();

						File file = new File("/mnt/sdcard/Download/ly.mp3");

						FileOutputStream fos = new FileOutputStream(file);

						int content = 0;

						while((content = is.read()) != -1) {
							System.out.print((char)content);
							fos.write((char)content);
							fos.flush();
						}

						fos.close();

						System.out.println("file was got");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
	}
}
